// 测评关系管理模块
console.log('Loading EvaluationRelationModule...');
const EvaluationRelationModule = {
    currentTab: 'dept',

    // 初始化
    init() {
        console.log('EvaluationRelationModule.init() called');
        this.switchTab('dept');
    },

    // Tab切换（兼容性方法）
    switchRelationTab(tabName) {
        this.switchTab(tabName);
    },

    // Tab切换
    switchTab(tabName) {
        console.log('EvaluationRelationModule.switchTab called with:', tabName);
        this.currentTab = tabName;
        
        // 切换Tab活动状态
        document.querySelectorAll('#evaluation-relation-management .tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('#evaluation-relation-management .tab-content').forEach(content => {
            content.classList.remove('active');
        });

        // 激活选中的Tab
        const targetTab = document.querySelector(`#evaluation-relation-management .tab[onclick*="${tabName}"]`);
        console.log('Target tab found:', targetTab);
        if (targetTab) {
            targetTab.classList.add('active');
        }
        const targetContent = document.getElementById(tabName + '-relation-tab');
        console.log('Target content found:', targetContent);
        if (targetContent) {
            targetContent.classList.add('active');
        }

        // 控制导出按钮显示
        const exportDeptBtn = document.getElementById('exportDeptBtn');
        const exportTeacherBtn = document.getElementById('exportTeacherBtn');
        
        if (tabName === 'dept') {
            if (exportDeptBtn) exportDeptBtn.style.display = 'block';
            if (exportTeacherBtn) exportTeacherBtn.style.display = 'none';
        } else if (tabName === 'teacher') {
            if (exportDeptBtn) exportDeptBtn.style.display = 'none';
            if (exportTeacherBtn) exportTeacherBtn.style.display = 'block';
        }

        // 加载对应数据
        if (tabName === 'dept') {
            console.log('Loading dept relation list...');
            this.loadDeptRelationList();
        } else if (tabName === 'teacher') {
            console.log('Loading teacher relation list...');
            this.loadTeacherRelationList();
        }
    },

    // ========== 测评关系生成 ==========
    generateDeptRelations() {
        if (!CommonModule.confirmAction('确认生成部门测评关系？此操作将重新生成所有部门间的测评关系。')) {
            return;
        }

        CommonModule.apiRequest('/relation/generate/dept', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('部门测评关系生成成功：' + data.message);
                this.loadDeptRelationList();
            } else {
                alert('生成失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '生成部门测评关系');
        });
    },

    generateTeacherRelations() {
        if (!CommonModule.confirmAction('确认生成教师测评关系？此操作将重新生成所有教师间的测评关系。')) {
            return;
        }

        CommonModule.apiRequest('/relation/generate/teacher', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('教师测评关系生成成功：' + data.message);
                this.loadTeacherRelationList();
            } else {
                alert('生成失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '生成教师测评关系');
        });
    },

    // ========== 部门测评关系管理 ==========
    loadDeptRelationList(page = 1) {
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 10);

        // 获取搜索条件
        const bcpbm = document.getElementById('relationEvaluateeSearch')?.value;
        const cpjs = document.getElementById('evaluatorSearch')?.value;
        const cpbs = document.getElementById('relationStatusSearch')?.value;
        if (bcpbm) params.append('bcpbm', bcpbm);
        if (cpjs) params.append('cpjs', cpjs);
        if (cpbs) params.append('cpbs', cpbs);

        CommonModule.apiRequest(`/relation/dept/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderDeptRelationTable(data.data.records || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        CommonModule.createPagination('deptRelationPagination', totalPages, page, (p) => this.loadDeptRelationList(p));
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载部门测评关系');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载部门测评关系');
            });
    },

    renderDeptRelationTable(relations) {
        const tbody = document.querySelector('#deptRelationsTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (relations && relations.length > 0) {
            relations.forEach(relation => {
                const row = document.createElement('tr');
                // 格式化测评时间
                const formatDate = (dateStr) => {
                    if (!dateStr) return '';
                    const date = new Date(dateStr);
                    return date.toLocaleDateString('zh-CN');
                };
                
                // 获取权重名称（如果后端没有提供，根据权重编号映射）
                const getWeightName = (cpqzbh) => {
                    const weightMap = {
                        '1': '领导评议',
                        '2': '服务对象评议', 
                        '3': '同事互评',
                        '4': '工作实践',
                        '5': '服务质量',
                        '6': '融合协作',
                        '7': '创新工作'
                    };
                    return weightMap[cpqzbh] || cpqzbh || '';
                };
                
                row.innerHTML = `
                    <td>${relation.bh || ''}</td>
                    <td>${relation.bcpbm || ''}</td>
                    <td>${relation.cpjs || ''}</td>
                    <td>${relation.cpjsbm || ''}</td>
                    <td>${relation.cpzbbh || ''}</td>
                    <td>${relation.cpqzbh || ''}</td>
                    <td>${getWeightName(relation.cpqzbh)}</td>
                    <td>${relation.totalscore || 0}</td>
                    <td>${relation.firstscore || 0}</td>
                    <td>${relation.twoscore || 0}</td>
                    <td>${relation.threescore || 0}</td>
                    <td>${relation.fourscore || 0}</td>
                    <td>${relation.cpbs === '1' ? '已测评' : '未测评'}</td>
                    <td>${formatDate(relation.cpsj)}</td>
                    <!--td>
                        <button class="btn btn-primary btn-small" onclick="EvaluationRelationModule.editDeptRelation('${relation.bh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="EvaluationRelationModule.deleteDeptRelation('${relation.bh}')">删除</button>
                    </td-->
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="15">暂无数据</td></tr>';
        }
    },

    showDeptRelationModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑部门测评关系' : '新增部门测评关系';
        
        const content = `
            <form id="deptRelationForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">关系编号</label>
                        <input type="text" name="bh" class="form-input" value="${isEdit ? data.bh : ''}" readonly>
                    </div>
                    <div class="form-group">
                        <label class="form-label">被测评部门编号</label>
                        <input type="text" name="bcpbmbh" class="form-input" value="${isEdit ? data.bcpbmbh : ''}" placeholder="请输入被测评部门编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">被测评部门</label>
                        <input type="text" name="bcpbm" class="form-input" value="${isEdit ? data.bcpbm : ''}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评教师编号</label>
                        <input type="text" name="cpjsbh" class="form-input" value="${isEdit ? data.cpjsbh : ''}" placeholder="请输入测评教师编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">测评教师</label>
                        <input type="text" name="cpjs" class="form-input" value="${isEdit ? data.cpjs : ''}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评教师部门编号</label>
                        <input type="text" name="cpjsbmbh" class="form-input" value="${isEdit ? data.cpjsbmbh : ''}" placeholder="请输入测评教师部门编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">测评教师部门</label>
                        <input type="text" name="cpjsbm" class="form-input" value="${isEdit ? data.cpjsbm : ''}" placeholder="请输入测评教师部门">
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评指标编号</label>
                        <input type="text" name="cpzbbh" class="form-input" value="${isEdit ? data.cpzbbh : ''}" placeholder="请输入测评指标编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">测评权重编号</label>
                        <select name="cpqzbh" class="form-input">
                            <option value="">请选择权重编号</option>
                            <option value="1" ${isEdit && data.cpqzbh === '1' ? 'selected' : ''}>1 - 领导评议</option>
                            <option value="2" ${isEdit && data.cpqzbh === '2' ? 'selected' : ''}>2 - 服务对象评议</option>
                            <option value="3" ${isEdit && data.cpqzbh === '3' ? 'selected' : ''}>3 - 同事互评</option>
                            <option value="4" ${isEdit && data.cpqzbh === '4' ? 'selected' : ''}>4 - 工作实践</option>
                            <option value="5" ${isEdit && data.cpqzbh === '5' ? 'selected' : ''}>5 - 服务质量</option>
                            <option value="6" ${isEdit && data.cpqzbh === '6' ? 'selected' : ''}>6 - 融合协作</option>
                            <option value="7" ${isEdit && data.cpqzbh === '7' ? 'selected' : ''}>7 - 创新工作</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">排序</label>
                        <input type="text" name="cppx" class="form-input" value="${isEdit ? data.cppx : ''}" placeholder="请输入排序">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">第一分数</label>
                        <input type="number" name="firstscore" class="form-input" value="${isEdit ? data.firstscore : 0}" min="0" max="100">
                    </div>
                    <div class="form-group">
                        <label class="form-label">第二分数</label>
                        <input type="number" name="twoscore" class="form-input" value="${isEdit ? data.twoscore : 0}" min="0" max="100">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">第三分数</label>
                        <input type="number" name="threescore" class="form-input" value="${isEdit ? data.threescore : 0}" min="0" max="100">
                    </div>
                    <div class="form-group">
                        <label class="form-label">第四分数</label>
                        <input type="number" name="fourscore" class="form-input" value="${isEdit ? data.fourscore : 0}" min="0" max="100">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">总分</label>
                        <input type="number" name="totalscore" class="form-input" value="${isEdit ? data.totalscore : 0}" min="0" max="400" readonly>
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评状态</label>
                        <select name="cpbs" class="form-input" required>
                            <option value="0" ${isEdit && data.cpbs === '0' ? 'selected' : ''}>未测评</option>
                            <option value="1" ${isEdit && data.cpbs === '1' ? 'selected' : ''}>已测评</option>
                        </select>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="EvaluationRelationModule.saveDeptRelation(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
        
        // 添加分数自动计算功能
        if (!isEdit) {
            this.addScoreCalculation();
        }
    },

    // 添加分数自动计算功能
    addScoreCalculation() {
        setTimeout(() => {
            const scoreInputs = ['firstscore', 'twoscore', 'threescore', 'fourscore'];
            const totalInput = document.querySelector('input[name="totalscore"]');
            
            scoreInputs.forEach(inputName => {
                const input = document.querySelector(`input[name="${inputName}"]`);
                if (input) {
                    input.addEventListener('input', () => {
                        this.calculateTotalScore();
                    });
                }
            });
        }, 100);
    },

    // 计算总分
    calculateTotalScore() {
        const scoreInputs = ['firstscore', 'twoscore', 'threescore', 'fourscore'];
        const totalInput = document.querySelector('input[name="totalscore"]');
        
        if (totalInput) {
            let total = 0;
            scoreInputs.forEach(inputName => {
                const input = document.querySelector(`input[name="${inputName}"]`);
                if (input && input.value) {
                    total += parseInt(input.value) || 0;
                }
            });
            totalInput.value = total;
        }
    },

    saveDeptRelation(isEdit) {
        const form = document.getElementById('deptRelationForm');
        const formData = new FormData(form);
        
        const relationData = {
            bh: isEdit ? window.currentEditData.bh : null,
            bcpbmbh: formData.get('bcpbmbh'),
            bcpbm: formData.get('bcpbm'),
            cpjsbh: formData.get('cpjsbh'),
            cpjs: formData.get('cpjs'),
            cpjsbmbh: formData.get('cpjsbmbh'),
            cpjsbm: formData.get('cpjsbm'),
            cpzbbh: formData.get('cpzbbh'),
            cpqzbh: formData.get('cpqzbh'),
            cppx: formData.get('cppx'),
            firstscore: parseInt(formData.get('firstscore')) || 0,
            twoscore: parseInt(formData.get('twoscore')) || 0,
            threescore: parseInt(formData.get('threescore')) || 0,
            fourscore: parseInt(formData.get('fourscore')) || 0,
            totalscore: parseInt(formData.get('totalscore')) || 0,
            cpbs: formData.get('cpbs')
        };

        const url = isEdit ?
            `/relation/dept/${window.currentEditData.bh}` :
            '/relation/dept';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(relationData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadDeptRelationList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存部门测评关系');
        });
    },

    editDeptRelation(bh) {
        CommonModule.apiRequest(`/relation/dept/${bh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showDeptRelationModal(data.data);
                } else {
                    alert('获取部门测评关系信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取部门测评关系详情');
            });
    },

    deleteDeptRelation(bh) {
        if (!CommonModule.confirmAction('确认删除该部门测评关系？删除后不可恢复。')) {
            return;
        }
        
        CommonModule.apiRequest(`/relation/dept/${bh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadDeptRelationList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除部门测评关系');
        });
    },

    // ========== 教师测评关系管理 ==========
    loadTeacherRelationList(page = 1) {
        console.log('loadTeacherRelationList called with page:', page);
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 10);

        // 获取搜索条件
        const bcpjs = document.getElementById('relationEvaluateeSearch')?.value;
        const cpjs = document.getElementById('evaluatorSearch')?.value;
        const cpbs = document.getElementById('relationStatusSearch')?.value;
        console.log('Search conditions:', { bcpjs, cpjs, cpbs });
        if (bcpjs) params.append('bcpjs', bcpjs);
        if (cpjs) params.append('cpjs', cpjs);
        if (cpbs) params.append('cpbs', cpbs);

        const url = `/relation/teacher/list?${params}`;
        console.log('API URL:', url);

        CommonModule.apiRequest(url)
            .then(response => response.json())
            .then(data => {
                console.log('Teacher relation API response:', data);
                if (data.code === 200 && data.data) {
                    this.renderTeacherRelationTable(data.data.records || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        CommonModule.createPagination('teacherRelationPagination', totalPages, page, (p) => this.loadTeacherRelationList(p));
                    }
                } else {
                    console.error('Teacher relation API error:', data);
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载教师测评关系');
                }
            })
            .catch(error => {
                console.error('Teacher relation request error:', error);
                CommonModule.handleApiError(error, '加载教师测评关系');
            });
    },

    renderTeacherRelationTable(relations) {
        console.log('renderTeacherRelationTable called with:', relations);
        const tbody = document.querySelector('#teacherRelationsTableContent table tbody');
        console.log('Found tbody element:', tbody);
        if (!tbody) {
            console.error('Teacher relation table tbody not found!');
            return;
        }

        tbody.innerHTML = '';
        if (relations && relations.length > 0) {
            console.log('Rendering', relations.length, 'teacher relations');
            relations.forEach(relation => {
                const row = document.createElement('tr');
                // 格式化测评时间
                const formatDate = (dateStr) => {
                    if (!dateStr) return '';
                    const date = new Date(dateStr);
                    return date.toLocaleDateString('zh-CN');
                };
                
                // 获取权重名称（如果后端没有提供，暂时显示权重编号）
                const getWeightName = (cpqzbh) => {
                    const weightMap = {
                        '1': '领导评议',
                        '2': '服务对象评议', 
                        '3': '同事互评',
                        '4': '工作实践',
                        '5': '服务质量',
                        '6': '融合协作',
                        '7': '创新工作'
                    };
                    return weightMap[cpqzbh] || cpqzbh || '';
                };
                
                row.innerHTML = `
                    <td>${relation.bh || ''}</td>
                    <td>${relation.bcpjs || ''}</td>
                    <td>${relation.bcpjsbm || ''}</td>
                    <td>${relation.cpjs || ''}</td>
                    <td>${relation.cpjsbm || ''}</td>
                    <td>${relation.cpzbbh || ''}</td>
                    <td>${relation.cpqzbh || ''}</td>
                    <td>${getWeightName(relation.cpqzbh)}</td>
                    <td>${relation.cppx || ''}</td>
                    <td>${relation.totalscore || 0}</td>
                    <td>${relation.firstscore || 0}</td>
                    <td>${relation.twoscore || 0}</td>
                    <td>${relation.threescore || 0}</td>
                    <td>${relation.fourscore || 0}</td>
                    <td>${relation.cpbs === '1' ? '已测评' : '未测评'}</td>
                    <td>${formatDate(relation.cpsj)}</td>
                    <!--td>
                        <button class="btn btn-primary btn-small" onclick="EvaluationRelationModule.editTeacherRelation('${relation.bh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="EvaluationRelationModule.deleteTeacherRelation('${relation.bh}')">删除</button>
                    </td-->
                `;
                tbody.appendChild(row);
            });
            console.log('Teacher relation table rendering completed');
        } else {
            console.log('No teacher relation data, showing empty message');
            tbody.innerHTML = '<tr><td colspan="17">暂无数据</td></tr>';
        }
    },

    showTeacherRelationModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑教师测评关系' : '新增教师测评关系';
        
        const content = `
            <form id="teacherRelationForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">关系编号</label>
                        <input type="text" name="bh" class="form-input" value="${isEdit ? data.bh : ''}" readonly>
                    </div>
                    <div class="form-group">
                        <label class="form-label">被测评教师编号</label>
                        <input type="text" name="bcpjsbh" class="form-input" value="${isEdit ? data.bcpjsbh : ''}" placeholder="请输入被测评教师编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">被测评教师</label>
                        <input type="text" name="bcpjs" class="form-input" value="${isEdit ? data.bcpjs : ''}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">被测评教师部门编号</label>
                        <input type="text" name="bcpjsbmbh" class="form-input" value="${isEdit ? data.bcpjsbmbh : ''}" placeholder="请输入被测评教师部门编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">被测评教师部门</label>
                        <input type="text" name="bcpjsbm" class="form-input" value="${isEdit ? data.bcpjsbm : ''}" placeholder="请输入被测评教师部门">
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评教师编号</label>
                        <input type="text" name="cpjsbh" class="form-input" value="${isEdit ? data.cpjsbh : ''}" placeholder="请输入测评教师编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">测评教师</label>
                        <input type="text" name="cpjs" class="form-input" value="${isEdit ? data.cpjs : ''}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评教师部门编号</label>
                        <input type="text" name="cpjsbmbh" class="form-input" value="${isEdit ? data.cpjsbmbh : ''}" placeholder="请输入测评教师部门编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">测评教师部门</label>
                        <input type="text" name="cpjsbm" class="form-input" value="${isEdit ? data.cpjsbm : ''}" placeholder="请输入测评教师部门">
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评指标编号</label>
                        <input type="text" name="cpzbbh" class="form-input" value="${isEdit ? data.cpzbbh : ''}" placeholder="请输入测评指标编号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">测评权重编号</label>
                        <select name="cpqzbh" class="form-input">
                            <option value="">请选择权重编号</option>
                            <option value="1" ${isEdit && data.cpqzbh === '1' ? 'selected' : ''}>1 - 领导评议</option>
                            <option value="2" ${isEdit && data.cpqzbh === '2' ? 'selected' : ''}>2 - 服务对象评议</option>
                            <option value="3" ${isEdit && data.cpqzbh === '3' ? 'selected' : ''}>3 - 同事互评</option>
                            <option value="4" ${isEdit && data.cpqzbh === '4' ? 'selected' : ''}>4 - 工作实践</option>
                            <option value="5" ${isEdit && data.cpqzbh === '5' ? 'selected' : ''}>5 - 服务质量</option>
                            <option value="6" ${isEdit && data.cpqzbh === '6' ? 'selected' : ''}>6 - 融合协作</option>
                            <option value="7" ${isEdit && data.cpqzbh === '7' ? 'selected' : ''}>7 - 创新工作</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">排序</label>
                        <input type="text" name="cppx" class="form-input" value="${isEdit ? data.cppx : ''}" placeholder="请输入排序">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">第一分数</label>
                        <input type="number" name="firstscore" class="form-input" value="${isEdit ? data.firstscore : 0}" min="0" max="100">
                    </div>
                    <div class="form-group">
                        <label class="form-label">第二分数</label>
                        <input type="number" name="twoscore" class="form-input" value="${isEdit ? data.twoscore : 0}" min="0" max="100">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">第三分数</label>
                        <input type="number" name="threescore" class="form-input" value="${isEdit ? data.threescore : 0}" min="0" max="100">
                    </div>
                    <div class="form-group">
                        <label class="form-label">第四分数</label>
                        <input type="number" name="fourscore" class="form-input" value="${isEdit ? data.fourscore : 0}" min="0" max="100">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">总分</label>
                        <input type="number" name="totalscore" class="form-input" value="${isEdit ? data.totalscore : 0}" min="0" max="400" readonly>
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评状态</label>
                        <select name="cpbs" class="form-input" required>
                            <option value="0" ${isEdit && data.cpbs === '0' ? 'selected' : ''}>未测评</option>
                            <option value="1" ${isEdit && data.cpbs === '1' ? 'selected' : ''}>已测评</option>
                        </select>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="EvaluationRelationModule.saveTeacherRelation(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
        
        // 添加分数自动计算功能
        if (!isEdit) {
            this.addTeacherScoreCalculation();
        }
    },

    // 添加教师分数自动计算功能
    addTeacherScoreCalculation() {
        setTimeout(() => {
            const scoreInputs = ['firstscore', 'twoscore', 'threescore', 'fourscore'];
            const totalInput = document.querySelector('input[name="totalscore"]');
            
            scoreInputs.forEach(inputName => {
                const input = document.querySelector(`input[name="${inputName}"]`);
                if (input) {
                    input.addEventListener('input', () => {
                        this.calculateTeacherTotalScore();
                    });
                }
            });
        }, 100);
    },

    // 计算教师总分
    calculateTeacherTotalScore() {
        const scoreInputs = ['firstscore', 'twoscore', 'threescore', 'fourscore'];
        const totalInput = document.querySelector('input[name="totalscore"]');
        
        if (totalInput) {
            let total = 0;
            scoreInputs.forEach(inputName => {
                const input = document.querySelector(`input[name="${inputName}"]`);
                if (input && input.value) {
                    total += parseInt(input.value) || 0;
                }
            });
            totalInput.value = total;
        }
    },

    saveTeacherRelation(isEdit) {
        const form = document.getElementById('teacherRelationForm');
        const formData = new FormData(form);
        
        const relationData = {
            bh: isEdit ? window.currentEditData.bh : null,
            bcpjsbh: formData.get('bcpjsbh'),
            bcpjs: formData.get('bcpjs'),
            bcpjsbmbh: formData.get('bcpjsbmbh'),
            bcpjsbm: formData.get('bcpjsbm'),
            cpjsbh: formData.get('cpjsbh'),
            cpjs: formData.get('cpjs'),
            cpjsbmbh: formData.get('cpjsbmbh'),
            cpjsbm: formData.get('cpjsbm'),
            cpzbbh: formData.get('cpzbbh'),
            cpqzbh: formData.get('cpqzbh'),
            cppx: formData.get('cppx'),
            firstscore: parseInt(formData.get('firstscore')) || 0,
            twoscore: parseInt(formData.get('twoscore')) || 0,
            threescore: parseInt(formData.get('threescore')) || 0,
            fourscore: parseInt(formData.get('fourscore')) || 0,
            totalscore: parseInt(formData.get('totalscore')) || 0,
            cpbs: formData.get('cpbs')
        };

        const url = isEdit ?
            `/relation/teacher/${window.currentEditData.bh}` :
            '/relation/teacher';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(relationData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadTeacherRelationList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存教师测评关系');
        });
    },

    editTeacherRelation(bh) {
        CommonModule.apiRequest(`/relation/teacher/${bh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showTeacherRelationModal(data.data);
                } else {
                    alert('获取教师测评关系信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取教师测评关系详情');
            });
    },

    deleteTeacherRelation(bh) {
        if (!CommonModule.confirmAction('确认删除该教师测评关系？删除后不可恢复。')) {
            return;
        }
        
        CommonModule.apiRequest(`/relation/teacher/${bh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadTeacherRelationList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除教师测评关系');
        });
    },

    // 搜索功能
    searchRelations() {
        if (this.currentTab === 'teacher') {
            this.loadTeacherRelationList(1);
        } else {
            this.loadDeptRelationList(1);
        }
    },

    // 导出部门测评关系
    exportDeptRelations() {
        try {
            // 获取当前搜索条件
            const bcpbm = document.getElementById('relationEvaluateeSearch').value;
            const cpjs = document.getElementById('evaluatorSearch').value;
            const cpbs = document.getElementById('relationStatusSearch').value;

            // 构建导出URL
            const params = new URLSearchParams();
            if (bcpbm) params.append('bcpbm', bcpbm);
            if (cpjs) params.append('cpjs', cpjs);
            if (cpbs) params.append('cpbs', cpbs);

            const exportUrl = `${CommonModule.globalConfig.apiBase}/relation/dept/export?${params.toString()}`;
            
            // 使用window.open方式下载
            window.open(exportUrl, '_blank');
            
            CommonModule.showSuccess('部门测评关系导出请求已发送');
        } catch (error) {
            console.error('导出部门测评关系失败:', error);
            CommonModule.showError('导出部门测评关系失败');
        }
    },

    // 导出教师测评关系
    exportTeacherRelations() {
        try {
            // 获取当前搜索条件
            const bcpjs = document.getElementById('relationEvaluateeSearch').value;
            const cpjs = document.getElementById('evaluatorSearch').value;
            const cpbs = document.getElementById('relationStatusSearch').value;

            // 构建导出URL
            const params = new URLSearchParams();
            if (bcpjs) params.append('bcpjs', bcpjs);
            if (cpjs) params.append('cpjs', cpjs);
            if (cpbs) params.append('cpbs', cpbs);

            const exportUrl = `${CommonModule.globalConfig.apiBase}/relation/teacher/export?${params.toString()}`;
            
            // 使用window.open方式下载
            window.open(exportUrl, '_blank');
            
            CommonModule.showSuccess('教师测评关系导出请求已发送');
        } catch (error) {
            console.error('导出教师测评关系失败:', error);
            CommonModule.showError('导出教师测评关系失败');
        }
    }
};

// 全局函数用于Tab切换
function switchRelationTab(tabName) {
    console.log('Global switchRelationTab called with:', tabName);
    if (typeof EvaluationRelationModule !== 'undefined') {
        EvaluationRelationModule.switchTab(tabName);
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

// 全局函数用于生成测评关系
function generateDeptRelations() {
    console.log('Global generateDeptRelations called');
    if (typeof EvaluationRelationModule !== 'undefined') {
        EvaluationRelationModule.generateDeptRelations();
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

function generateTeacherRelations() {
    console.log('Global generateTeacherRelations called');
    if (typeof EvaluationRelationModule !== 'undefined') {
        EvaluationRelationModule.generateTeacherRelations();
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

// 全局导出函数
function exportDeptRelations() {
    console.log('Global exportDeptRelations called');
    if (typeof EvaluationRelationModule !== 'undefined') {
        EvaluationRelationModule.exportDeptRelations();
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

function exportTeacherRelations() {
    console.log('Global exportTeacherRelations called');
    if (typeof EvaluationRelationModule !== 'undefined') {
        EvaluationRelationModule.exportTeacherRelations();
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

// 根据当前Tab导出对应数据
function exportCurrentTabRelations() {
    console.log('Global exportCurrentTabRelations called');
    if (typeof EvaluationRelationModule !== 'undefined') {
        if (EvaluationRelationModule.currentTab === 'teacher') {
            EvaluationRelationModule.exportTeacherRelations();
        } else {
            EvaluationRelationModule.exportDeptRelations();
        }
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

function searchRelations() {
    console.log('Global searchRelations called');
    if (typeof EvaluationRelationModule !== 'undefined') {
        EvaluationRelationModule.searchRelations();
    } else {
        console.error('EvaluationRelationModule is not defined!');
    }
}

// 导出模块
console.log('Exporting EvaluationRelationModule to window...');
window.EvaluationRelationModule = EvaluationRelationModule;
console.log('EvaluationRelationModule exported:', typeof window.EvaluationRelationModule); 